// pages/core/profile/profile.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoggedIn: false,
    userInfo: {
      userId: '',
      nickName: '',
      avatarUrl: '',
      phone: '',
      memberLevel: 0
    },
    memberLevel: '普通会员',
    orderTypes: [
      { type: 'pending_payment', name: '待付款', icon: 'money', count: 0 },
      { type: 'pending_delivery', name: '待发货', icon: 'shop', count: 0 },
      { type: 'pending_receipt', name: '待收货', icon: 'gift', count: 0 },  // 从deliver改为inbox
      { type: 'completed', name: '已完成', icon: 'check', count: 0 },
      { type: 'after_sale', name: '售后', icon: 'service', count: 0 }
    ],
    services: [
      { id: 1, name: '我的收藏', icon: 'heart', url: '/pages/transaction/favorites/favorites' },
      { id: 2, name: '优惠券', icon: 'discount', url: '/pages/transaction/coupons/coupons' },
      { id: 3, name: '积分商城', icon: 'shop', url: '/pages/features/points/points' },
      { id: 4, name: '我的足迹', icon: 'browse', url: '/pages/transaction/footprint/footprint' },  // 从footprint改为browse
      { id: 5, name: '地址管理', icon: 'location', url: '/pages/transaction/address/address' },
      { id: 6, name: '我的评价', icon: 'chat', url: '/pages/social/my_reviews/my_reviews' },
      { id: 7, name: '旅行日记', icon: 'edit', url: '/pages/social/travel_notes/travel_notes' },
      { id: 8, name: '健康档案', icon: 'heart', url: '/pages/features/health_record/health_record' }
    ],
    moreServices: [
      { id: 1, name: '帮助中心', icon: 'help-circle', url: '/pages/settings/help_center/help_center' },
      { id: 2, name: '联系客服', icon: 'service', url: '/pages/social/customer_service/customer_service' },
      { id: 3, name: '意见反馈', icon: 'chat', url: '/pages/settings/feedback/feedback' },
      { id: 4, name: '设置', icon: 'setting', url: '/pages/settings/settings/settings' }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLoginStatus();
    this.getOrderCounts();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.checkLoginStatus();
    this.getOrderCounts();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (userInfo && token) {
      this.setData({
        isLoggedIn: true,
        userInfo: userInfo,
        memberLevel: this.getMemberLevelName(userInfo.memberLevel)
      });
    } else {
      this.setData({
        isLoggedIn: false,
        userInfo: {
          userId: '',
          nickName: '',
          avatarUrl: '',
          phone: '',
          memberLevel: 0
        },
        memberLevel: '普通会员'
      });
    }
  },
  
  // 获取会员等级名称
  getMemberLevelName(level) {
    const levelMap = {
      0: '普通会员',
      1: '银卡会员',
      2: '金卡会员',
      3: '钻石会员'
    };
    return levelMap[level] || '普通会员';
  },
  
  // 获取订单数量
  getOrderCounts() {
    if (!this.data.isLoggedIn) {
      return;
    }
    
    // 此处预留接口调用 - 获取订单数量
    const getOrderCountsPromise = () => {
      // 未来实现: 调用云函数获取订单数量
      // 模拟数据
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({
            code: 0,
            message: 'success',
            data: {
              pending_payment: 1,
              pending_delivery: 2,
              pending_receipt: 0,
              completed: 5,
              after_sale: 0
            }
          });
        }, 500);
      });
    };
    
    getOrderCountsPromise()
      .then((res) => {
        if (res.code === 0) {
          const orderCounts = res.data;
          const orderTypes = this.data.orderTypes.map((item) => {
            return {
              ...item,
              count: orderCounts[item.type] || 0
            };
          });
          
          this.setData({
            orderTypes
          });
        }
      })
      .catch((error) => {
        console.error('获取订单数量失败:', error);
      });
  },
  
  // 头像点击事件
  onAvatarTap() {
    if (!this.data.isLoggedIn) {
      this.navigateToLogin();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/settings/user_info/user_info'
    });
  },
  
  // 用户名点击事件
  onLoginTap() {
    if (!this.data.isLoggedIn) {
      this.navigateToLogin();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/settings/user_info/user_info'
    });
  },
  
  // 跳转到登录页
  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/core/login/login'
    });
  },
  
  // 查看全部订单
  onViewAllOrders() {
    if (!this.data.isLoggedIn) {
      this.navigateToLogin();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/transaction/orders/orders'
    });
  },
  
  // 订单类型点击事件
  onOrderTypeTap(e) {
    if (!this.data.isLoggedIn) {
      this.navigateToLogin();
      return;
    }
    
    const { type } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/transaction/orders/orders?type=${type}`
    });
  },
  
  // 服务项点击事件
  onServiceTap(e) {
    if (!this.data.isLoggedIn) {
      this.navigateToLogin();
      return;
    }
    
    const { service } = e.currentTarget.dataset;
    wx.navigateTo({
      url: service.url
    });
  },
  
  // 更多服务点击事件
  onMoreServiceTap(e) {
    const { service } = e.currentTarget.dataset;
    
    // 部分功能需要登录
    if ((service.id === 2 || service.id === 3) && !this.data.isLoggedIn) {
      this.navigateToLogin();
      return;
    }
    
    wx.navigateTo({
      url: service.url
    });
  }
})